import type {
  Action,
  Middleware,
  MiddlewareAPI,
  ThunkAction,
} from "@reduxjs/toolkit"
import { combineSlices, configureStore, isRejected } from "@reduxjs/toolkit"
import { setupListeners } from "@reduxjs/toolkit/query"
import { userSlice } from "@/app/user/userSlice"
import { userApi } from "@/app/user/userApi"
import { authApi } from "@/app/auth/authApi"
import { toast } from "@/shared/ui/use-toast"
import { animalsApi } from "@/app/animals/animalsApi"
// `combineSlices` automatically combines the reducers using
// their `reducerPath`s, therefore we no longer need to call `combineReducers`.
const rootReducer = combineSlices(userSlice, userApi, authApi, animalsApi)
// Infer the `RootState` type from the root reducer
export type RootState = ReturnType<typeof rootReducer>

export const rtkQueryErrorLogger: Middleware =
  (api: MiddlewareAPI) => next => action => {
    // isRejectedWithValue Or isRejected
    if (isRejected(action)) {
      const { message } = action?.payload?.data?.error
      switch (message) {
        case "Email or Username are already taken":
          toast({
            variant: "destructive",
            title: "Данный Email уже используется другим пользователем",
          })
          break
        case "You have already created the request":
          toast({
            variant: "destructive",
            title: "Вы уже создали заявку, для продолжения удалите предыдущую",
          })
          break
        default:
          toast({
            variant: "destructive",
            title: "Что-то пошло не так",
          })
          break
      }
      if (action.payload?.status === 401) {
        console.log("error auth")
      }
    }

    return next(action)
  }

// The store setup is wrapped in `makeStore` to allow reuse
// when setting up tests that need the same store config
export const makeStore = (preloadedState?: Partial<RootState>) => {
  const store = configureStore({
    reducer: rootReducer,
    // Adding the api middleware enables caching, invalidation, polling,
    // and other useful features of `rtk-query`.
    middleware: getDefaultMiddleware => {
      return getDefaultMiddleware().concat(
        authApi.middleware,
        userApi.middleware,
        animalsApi.middleware,
        rtkQueryErrorLogger,
      )
    },
    preloadedState,
  })
  // configure listeners using the provided defaults
  // optional, but required for `refetchOnFocus`/`refetchOnReconnect` behaviors
  setupListeners(store.dispatch)
  return store
}

export const store = makeStore()

// Infer the type of `store`
export type AppStore = typeof store
// Infer the `AppDispatch` type from the store itself
export type AppDispatch = AppStore["dispatch"]
export type AppThunk<ThunkReturnType = void> = ThunkAction<
  ThunkReturnType,
  RootState,
  unknown,
  Action
>
